package com.steshov.Everything.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.steshov.Everything.entity.User;
import com.steshov.Everything.service.UserService;
import com.steshov.Everything.util.App;
import com.steshov.Everything.util.DataBaseException;

@Controller
public class IndexController {

	@Autowired
	UserService service;

	final String data = "data";

	@RequestMapping("index")
	protected ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		if (App.isAjax(request)) {
			ModelAndView view = new ModelAndView("ajax");
			if (StringUtils.isBlank(login)) {
				view.addObject(data, "emptyLogin");
			} else if (StringUtils.isBlank(password)) {
				view.addObject(data, "emptyPassword");
			} else {
				User user = service.authorized(login, password);
				if (user == null) {
					view.addObject(data, "Не правильный логин или пароль!");
				} else {
					HttpSession session = request.getSession();
					view = new ModelAndView("ajax");
					session.setAttribute("user", user);
					view.addObject("data", "success");
				}

			}
			return view;
		}
		return new ModelAndView("index");

	}

	@RequestMapping("logout")
	protected ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		session.invalidate();
		return new ModelAndView("index");
	}

	@RequestMapping("register")
	protected ModelAndView registrate(HttpServletRequest request,
			HttpServletResponse response) {

		ModelAndView view = new ModelAndView("index");
		if (App.isAjax(request)) {
			String login = request.getParameter("regLogin");
			String pass = request.getParameter("regPassword");
			String name = request.getParameter("regName");
			String mail = request.getParameter("regMail");

			User user = new User(login, name, pass, mail);
			try {
				view = new ModelAndView("ajax");
				service.createuser(user);
				// view.addObject("user", user);
				view.addObject("data", "success");
			} catch (DataBaseException e) {
				view.addObject(data, e);
			}
		}
		return view;
	}

	public UserService getService() {
		return service;
	}

	public void setService(UserService service) {
		this.service = service;
	}

}
